﻿using FasterBuild;
using FileSynchronization.Entity;
using FileSynchronization.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FileSynchronization.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("User")]
    [ApiController]
    public class UserController : DataAccess
    {
        private IJwtHelper jwtHelper;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jwtHelper"></param>
        public UserController(IJwtHelper jwtHelper)
        {
            this.jwtHelper = jwtHelper;
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="OutPutException"></exception>
        [HttpPost("Token"), AllowAnonymous]
        public async Task<string> GetToken([FromBody] UserLoginInput input)
        {
            try
            {
                if (input == null
                    || string.IsNullOrEmpty(input.UserName)
                    || string.IsNullOrEmpty(input.PassWord)
                    || !Enum.IsDefined(input.Type))
                {
                    throw new OutPutException("参数错误");
                }

                var passWord = CommonHelper.GetMD5Hash(input.PassWord);

                var userData = await Db.Queryable<User, UserType>((u, ut) => new object[]
                  {
                    JoinType.Left,u.ID==ut.UserID && ut.Type == input.Type
                  }).Where((u, ut) => u.Name == input.UserName && u.PassWord == passWord)
                  .Select((u, ut) => new
                  {
                      u.ID,
                      Type = SqlFunc.IIF(SqlFunc.IsNullOrEmpty(ut.Type), default(SyncType), ut.Type)
                  })
                 .FirstAsync();

                if (userData is null) throw new OutPutException("用户名或密码错误！");

                if (userData.Type is default(SyncType)) throw new OutPutException("没有发布该项目类型的权限！");

                return jwtHelper.Encrypt(new { UserID = userData.ID });
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "GetToken Error");
                throw;
            }
        }
    }
}
